package com.uzai.console.service.pdd.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.uzai.common.enums.OrderReStatusEnum;
import com.uzai.common.enums.OrderStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.feign.pddorder.PddOrderSettledDto;
import com.uzai.console.dto.jd.jdorder.JdFindUnReceicedDto;
import com.uzai.console.dto.pdd.pddorder.PddFindUnReceicedDto;
import com.uzai.console.dto.pdd.pddorder.PddOrderDownLoadDto;
import com.uzai.console.dto.feign.pddorder.PddOrderPullDto;
import com.uzai.console.entity.JdOrder;
import com.uzai.console.entity.PddOrder;
import com.uzai.console.entity.PddToken;
import com.uzai.console.mapper.PddOrderMapper;
import com.uzai.console.mapper.PddTokenMapper;
import com.uzai.console.para.JdOrderRemoteApiPara;
import com.uzai.console.para.PddOrderByOrderSnRemoteApiPara;
import com.uzai.console.para.PddOrderRemoteApiPara;
import com.uzai.console.service.feign.PddOrderFeignService;
import com.uzai.console.service.remoteapi.PddOrderRemoteApiService;
import com.uzai.console.service.pdd.PddOrderSyncService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: liuqi
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class PddOrderSyncServiceImpl implements PddOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(PddOrderSyncServiceImpl.class);

    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private PddOrderRemoteApiService pddOrderRemoteApiService;
    @Autowired
    private PddOrderFeignService pddOrderFeignService;


    /**
     * 手动下载单个拼多多联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder(PddOrderDownLoadDto pddOrderDownLoadDto, Long tokenId) {

        //调用订单业务库服务器
        PddToken pddToken = pddTokenMapper.selectById(tokenId, pddOrderDownLoadDto.getMerId());
        if(pddToken != null){
            try {
                PddOrderPullDto pddOrderPullDto = new PddOrderPullDto();
                pddOrderPullDto.setTokenId(pddToken.getDefPid());
                pddOrderPullDto.setPlatform("pdd");
                pddOrderPullDto.setStartTime(pddOrderDownLoadDto.getQueryStartTime());
                pddOrderPullDto.setEndTime(pddOrderDownLoadDto.getQueryEndTime());
                //时间类型 0订单库入库时间， 1订单库更新时间， 2订单创建时间， 3订单最后更新时间， 4订单付款时间， 5订单完成（收货）时间， 6订单结算时间，7订单维权创建时间，8订单维权完成时间")
                Integer timeType = 2;
                if(pddOrderDownLoadDto.getQueryTimeType() == 1){ //创建时间
                    timeType = 2;
                }else if(pddOrderDownLoadDto.getQueryTimeType() == 2){ //付款时间
                    timeType = 4;
                }else if(pddOrderDownLoadDto.getQueryTimeType() == 3){ //结算时间
                    timeType = 6;
                }
                pddOrderPullDto.setTimeType(timeType);
                //请求订单拉取接口
                pddOrderFeignService.pull(pddOrderPullDto);
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        //调用订单拉取库服务器
        if(pddToken != null){
            //调用订单拉取库服务器
            PddOrderRemoteApiPara pddOrderRemoteApiPara = new PddOrderRemoteApiPara();
            pddOrderRemoteApiPara.setQueryStartTime(pddOrderDownLoadDto.getQueryStartTime());
            pddOrderRemoteApiPara.setQueryEndTime(pddOrderDownLoadDto.getQueryEndTime());
            pddOrderRemoteApiService.remoteDownload(pddOrderRemoteApiPara);
        }

    }

    /**
     * 异步手动下载多个拼多多联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddOrderDownLoadDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void downloadOrderListSync(PddOrderDownLoadDto pddOrderDownLoadDto) {
        if(pddOrderDownLoadDto.getIdList() != null && pddOrderDownLoadDto.getIdList().size() > 0){
            for (Long id : pddOrderDownLoadDto.getIdList()){
                try {
                    downloadOrder(pddOrderDownLoadDto, id);
                }catch (Exception e){
                    logger.error("-------updatePddOrderUnReceivedList is error pddTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 远程调用订单库API，手动更新单个订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddOrder
     * @return null
     */
    @Override
    public void updatePddOrder(PddOrder pddOrder) {

        //判断订单存在或者已删除
        if(pddOrder == null){
           return;
        }

        //判断订单联盟是否存在
        if(StringUtils.isBlank(pddOrder.getPid())){
            return;
        }

        //订单联盟
        PddToken pddToken = pddTokenMapper.selectByDefPid(pddOrder.getPid());
        if(pddToken == null){
            return;
        }

        //调用订单拉取库服务器
        PddOrderByOrderSnRemoteApiPara pddOrderByOrderSnRemoteApiPara = new PddOrderByOrderSnRemoteApiPara();
        pddOrderByOrderSnRemoteApiPara.setAccessToken(pddToken.getAccessToken());
        pddOrderByOrderSnRemoteApiPara.setOrderSn(pddOrder.getChildOrderNo());
        pddOrderRemoteApiService.remoteDownloadByOrderSn(pddOrderByOrderSnRemoteApiPara);
    }

    @Override
    public void uploadPddOrderSettingSync(Long merId, int day, int status, List<Integer> sourceStatus) {
        if (merId == null) {
            return;
        }
        //设置结束时间为day天前
        int endTime = DateUtil.getNowTime() - day * 24 * 3600;
        pddOrderMapper.updateStatusPayCompleteToSettle(null, endTime, null, merId, status, sourceStatus);
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updatePddOrderUnReceivedListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        pddFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        pddFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        pddFindUnReceicedDto.setStatus(0);
        List<PddOrder> pddOrderList =  pddOrderMapper.findUnReceivedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    updatePddOrder(pddOrder);
                }catch (Exception e){
                    logger.error("-------updatePddOrderUnReceivedListSync is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updatePddOrderFreezedListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        pddFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        pddFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（已收货）
        pddFindUnReceicedDto.setStatus(1);
        List<PddOrder> pddOrderList =  pddOrderMapper.findFreezedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    updatePddOrder(pddOrder);
                }catch (Exception e){
                    logger.error("-------updatePddOrderFreezedListSync is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updatePddOrderUnReceivedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        pddFindUnReceicedDto.setQueryStartTime(startTime);
        pddFindUnReceicedDto.setQueryEndTime(endTime);
        pddFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        pddFindUnReceicedDto.setStatus(0);
        List<PddOrder> pddOrderList =  pddOrderMapper.findUnReceivedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    updatePddOrder(pddOrder);
                }catch (Exception e){
                    logger.error("-------updatePddOrderUnReceivedListSync is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updatePddOrderUnReceivedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        pddFindUnReceicedDto.setQueryStartTime(startTime);
        pddFindUnReceicedDto.setQueryEndTime(endTime);
        pddFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        pddFindUnReceicedDto.setStatus(0);
        List<PddOrder> pddOrderList =  pddOrderMapper.findUnReceivedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    //订单状态为0-付款状态时，才能确认收货
                    if(pddOrder.getStatus() == 0){
                        //调用确认收货接口
                        PddOrderSettledDto pddOrderSettledDto = new PddOrderSettledDto();
                        pddOrderSettledDto.setMerId(pddOrder.getMerId());
                        pddOrderSettledDto.setOrderId(pddOrder.getParentOrderNo());
                        pddOrderSettledDto.setChildOrderId(pddOrder.getChildOrderNo());
                        UzaiRespVo<Object> result =  pddOrderFeignService.settled(pddOrderSettledDto);
                        logger.info("---发送修改拼多多订单确认收货-para={}, result={}", JSONObject.toJSONString(pddOrderSettledDto), JSONObject.toJSONString(result));
                        if(result.getCode() != 200){
                            throw  new BusinessException(result.getCode(), result.getMsg());
                        }
                    }
                }catch (Exception e){
                    logger.error("-------updatePddOrderUnReceivedListSync_settle is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updatePddOrderFreezedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        pddFindUnReceicedDto.setQueryStartTime(startTime);
        pddFindUnReceicedDto.setQueryEndTime(endTime);
        pddFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        pddFindUnReceicedDto.setStatus(1);
        List<PddOrder> pddOrderList =  pddOrderMapper.findFreezedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    updatePddOrder(pddOrder);
                }catch (Exception e){
                    logger.error("-------updatePddOrderFreezedListSync is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updatePddOrderFreezedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        pddFindUnReceicedDto.setQueryStartTime(startTime);
        pddFindUnReceicedDto.setQueryEndTime(endTime);
        pddFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        pddFindUnReceicedDto.setStatus(1);
        List<PddOrder> pddOrderList =  pddOrderMapper.findFreezedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    //先修改订单状态为0-付款状态时，才能确认收货
                    pddOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    pddOrder.setUpdateTime(DateUtil.getNowTime());
                    pddOrderMapper.updateStatus(pddOrder);
                    //调用确认收货接口
                    PddOrderSettledDto pddOrderSettledDto = new PddOrderSettledDto();
                    pddOrderSettledDto.setMerId(pddOrder.getMerId());
                    pddOrderSettledDto.setOrderId(pddOrder.getParentOrderNo());
                    pddOrderSettledDto.setChildOrderId(pddOrder.getChildOrderNo());
                    UzaiRespVo<Object> result =  pddOrderFeignService.settled(pddOrderSettledDto);
                    logger.info("---发送修改拼多多订单确认收货-para={}, result={}", JSONObject.toJSONString(pddOrderSettledDto), JSONObject.toJSONString(result));
                    if(result.getCode() != 200){
                        throw  new BusinessException(result.getCode(), result.getMsg());
                    }
                }catch (Exception e){
                    logger.error("-------updatePddOrderFreezedListSync_settle is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updatePddOrderRefundingListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        pddFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        pddFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        pddFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<PddOrder> pddOrderList =  pddOrderMapper.findUnReceivedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    updatePddOrder(pddOrder);
                }catch (Exception e){
                    logger.error("-------updatePddOrderRefundingListSync is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updatePddOrderRefundingListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        pddFindUnReceicedDto.setQueryStartTime(startTime);
        pddFindUnReceicedDto.setQueryEndTime(endTime);
        pddFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        pddFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<PddOrder> pddOrderList =  pddOrderMapper.findUnReceivedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    updatePddOrder(pddOrder);
                }catch (Exception e){
                    logger.error("-------updatePddOrderRefundingListSync is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    public void updatePddOrderRefundingListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        PddFindUnReceicedDto pddFindUnReceicedDto = new PddFindUnReceicedDto();
        pddFindUnReceicedDto.setMerId(merId);
        pddFindUnReceicedDto.setQueryStartTime(startTime);
        pddFindUnReceicedDto.setQueryEndTime(endTime);
        pddFindUnReceicedDto.setUserId(userId);
        //查询维权中订单
        pddFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        //根据订单返利状态查询
        pddFindUnReceicedDto.setReStatusList(Lists.newArrayList(OrderReStatusEnum.RE_STATUS_NO_VALUE, OrderReStatusEnum.RE_STATUS_FROZEN_VALUE));
        List<PddOrder> pddOrderList =  pddOrderMapper.findUnReceivedList(pddFindUnReceicedDto);
        if(pddOrderList != null){
            for (PddOrder pddOrder : pddOrderList){
                try {
                    //先修改订单状态为0-付款状态时，才能确认收货
                    pddOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    pddOrder.setUpdateTime(DateUtil.getNowTime());
                    pddOrderMapper.updateStatus(pddOrder);
                    //调用确认收货接口
                    PddOrderSettledDto pddOrderSettledDto = new PddOrderSettledDto();
                    pddOrderSettledDto.setMerId(pddOrder.getMerId());
                    pddOrderSettledDto.setOrderId(pddOrder.getParentOrderNo());
                    pddOrderSettledDto.setChildOrderId(pddOrder.getChildOrderNo());
                    UzaiRespVo<Object> result =  pddOrderFeignService.settled(pddOrderSettledDto);
                    logger.info("---发送修改拼多多订单确认收货-para={}, result={}", JSONObject.toJSONString(pddOrderSettledDto), JSONObject.toJSONString(result));
                    if(result.getCode() != 200){
                        throw  new BusinessException(result.getCode(), result.getMsg());
                    }
                }catch (Exception e){
                    logger.error("-------updatePddOrderRefundingListSync_settle is error ordersn={}, error={}", pddOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

}
